<?php

namespace App\Services;

use AntChain\ATO\Client as AntChainATOClient;

use AntChain\ATO\Models\Config;
use AntChain\ATO\Models\SyncTradeRequest;
use AntChain\ATO\Models\RepayWithholdPlanRequest;
use AntChain\ATO\Models\UnbindWithholdSignRequest;
use AntChain\ATO\Models\CreateWithholdSignRequest;
use AntChain\ATO\Models\QueryWithholdSignRequest;
use AntChain\ATO\Models\CancelWithholdPlanRequest;
use AntChain\ATO\Models\ConfirmWithholdSignasyncunsignRequest;
use AntChain\ATO\Models\AuthSignFlowRequest;
use AntChain\ATO\Models\SyncFundSplittingRequest;
use AntChain\ATO\Models\GetSignFlowRequest;
use AntChain\ATO\Models\GetTradeRequest;
use AntChain\ATO\Models\SyncFrontTradeRequest;
use AntChain\ATO\Models\SubmitFrontSignRequest;
use AntChain\ATO\Models\SubmitSignFlowRequest;
use AntChain\ATO\Models\UploadSignTemplateRequest;
use App\Models\OrderLease;
use AntChain\ATO\Models\AllSignTemplateRequest;
use AntChain\ATO\Models\RetryWithholdPlanRequest;
use AntChain\ATO\Models\GetTradeUserperformanceRequest;
use AntChain\ATO\Models\CreateWithholdRefundRequest;
use AntChain\ATO\Models\QueryWithholdRefundRequest;



class AntchainAtoServicejuzu
{
    /**
     * 开发环境三要素密钥
     */
    private static  $DEV_PUK = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5czwxivEfJOfIp+vFB8NZee16ORu+cni2mLkAfqcDCGFPARkX9bejm8vJ3fnEww7Rr0PvY5DiWhtdfpUz+Wjvb6u2a9N23ltw84h6eMQ2lGjPSWoiqd4mKqsaY2FGzqp0Q9vrZgzU2qcioNGJMA1BG+s6xXK+xX/3vY+Dma4EXmB5bupdi/5fNNewl2OKyN6pKbDfir8VkPRgByUxcM05a+38x0+eiaqSFEsG4SXAePbwOACmIWuddenTJTgNZvBSBiFImDLDhOa49t2hYeXA4u+Gu4vRFKa4TkVA/rLW0Fe9NSOwX4Ehr01T93wssunMYcF3QWhcx4s1KvDc6HUEwIDAQAB";

    /**
     * 生产环境三要素密钥
     */
    private static  $PROD_PUK = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvE0ZMiSiRVlv68nb9gjigDYfNDDmWOX6vdHLHROCRneMK66QCJkErNzGQ5W+50CjPqv8V3QulDdawOsCsWBL+I+mn3WsOH1WZHK7jqEYUvT6tr2s9dNge6GeVUqg4R3ojoqv5LHryEFJuflr7zJdxhyt0Slo7gaPPjNqJtfUERuhbbSzRMC5sKLA5QLCj47VDjHtFBtoYeidarFZlDYUSNSH05O0SszDeLiCU5AlN/iHm84RaJO2GdMtj0dcVebxJqoDcA+Aao07lQomq5mhNXioYCDzBoNMzqqK98yovFEOueh63DSQ1PE7YJ7wLfw4egbxMWzFQ2RyaIduSQqR/QIDAQAB";

    private  static $client;

    public static function main($order)
    {
        // 生成订单id(随机)
//        $orderId = "96D89B8141A193013C4BD20EA5DA4";
//        // 一个订单只能选择「前置签署订单流程」or「后置签署订单流程」
//        // 前置签署流程demo
//        self::frontOrderFlow($orderId);
        // 后置签署流程demo
        return self::behindOrderFlow($order);
    }

    public static function AllSignTemplateRequest(){
        $client = self::getSandboxClient();
        $allSignTemplateRequest = new AllSignTemplateRequest([
            "contractType" => "COMMON",
            "fund_type"=>"NON_FINANCE",
            "merchantId" => "91331081MACQAYBA18"
        ]);
        $res=$client->allSignTemplate($allSignTemplateRequest);
        return obToArray($res);
    }

    /**
     * 创建合同
     * 后置订单流程
     * @param  $orderId
     */
    public static function createFlowOneStepShopThree($order)
    {
        $res=self::syncBehindOrder($order);
//       dd($res);
        // 发起后置合同签署
        $signNo = self::submitBehindSignFlow($order);
//        // 查询合同是否签署完成
        dd($signNo);

    }

    /**
     * 后置订单流程
     * @param  $orderId
     */
    public static function behindOrderFlow($order,$shop_user=[])
    {
//        // 同步后置订单
        $res=self::syncBehindOrder($order);
        dd($res);
        // 发起后置合同签署
        $signNo = self::submitBehindSignFlow($order);
        // 查询合同是否签署完成
        dd($signNo);
//        $signNo= self::querySignFlow('10060701000001783810357923561472');
//        dd($signNo);
        // 发起代扣签约请求
        $res=self::createWithholdSign($order['trade_no']);
        dd($res);

        //查询订单信息
//        $res= self::queryOrder($order['trade_no']);
//        var_dump(json_decode($res['responseData'],true));
//        return $res;
//        dd($res);
        // 查询代扣签约结果
//      $res= self::queryWithholdSign($order['trade_no']);
//     dd($res);
        // 如有需要：清偿清欠8);
//        $res=self::repayWithholdPlan($order['trade_no'], 1, 1);
//        dd($res);
//        dd($res);

//        $res=self::retryWithholdPlan($order['trade_no'],1);
//        dd($res);
        // 如有需要：取消代扣计划
        self::cancelWithholdPlan($orderId);
        // 如有需要：主动发起代扣解约
        self::unbindWithholdSign($orderId);
        // 如有需要：同意异步解约
        self::asyncUnbindConfirm($orderId, "AGREE", null, 1, null);
        // 如有需要：拒绝异步解约
        self::asyncUnbindConfirm($orderId, "REFUSE", "LEASE", 8, "USER_OWE_MONEY");
        // 关闭订单
        self::closeOrder($orderId);
    }

    /**
     * 代扣计划重试
     * @param string[] $args
     */
    public static function retryWithholdPlan($orderId,$periodNum){
        $retryWithholdPlanRequest = new RetryWithholdPlanRequest([
            "periodNum" => $periodNum,
            "orderId" => $orderId
        ]);
        $client = self::getSandboxClient();
        $res=$client->retryWithholdPlan($retryWithholdPlanRequest);
        return obToArray($res);
    }
    /**
     * 前置订单流程
     *
     * @param orderId
     * @
     */
    private static function frontOrderFlow($orderId)
    {
        // 同步前置订单
        self::syncFrontOrder($orderId);
        // 发起前置合同签署
        $signNo = self::submitFrontSignFlow($orderId);
        // 发起代扣签约请求
        self::createWithholdSign($orderId);
        // 查询代扣签约结果
        self::queryWithholdSign($orderId);
        // 代扣签约完成后，落签合同
        self::callAuthSignField($signNo, "jiafang");
        // 如果需要多方落签的情况
        self::callAuthSignField($signNo, "bingfang");
        // 如有需要：清偿清欠
        self::repayWithholdPlan($orderId, 1, 8);
        // 如有需要：取消代扣计划
        self::cancelWithholdPlan($orderId);
        // 如有需要：主动发起代扣解约
        self::unbindWithholdSign($orderId);
        // 如有需要：同意异步解约
        self::asyncUnbindConfirm($orderId, "AGREE", null, 1, null);
        // 如有需要：拒绝异步解约
        self::asyncUnbindConfirm($orderId, "REFUSE", "LEASE", 8, "USER_OWE_MONEY");
        // 关闭订单
        self::closeOrder($orderId);
    }


    //退款申请
    public static function createWithholdRefund($orderId,$periodNum,$refundMoney){
        $createWithholdRefundRequest = new CreateWithholdRefundRequest([
            "periodNum" => $periodNum,
            "refundRequestNo" => $orderId.$periodNum.'-1',
            "refundMoney" => $refundMoney,
            "refundReason" => "退款",
            "orderId" =>$orderId
        ]);
        $client = self::getSandboxClient();
        $resp=$client->createWithholdRefund($createWithholdRefundRequest);
        return obToArray($resp);
    }
    //查询退款申请
    public static function queryWithholdRefund($orderId,$periodNum){
        $queryWithholdRefundRequest = new QueryWithholdRefundRequest([
            "periodNum" => $periodNum,
            "refundRequestNo" =>$orderId.$periodNum.'-1',
            "orderId" =>$orderId
        ]);
        $client = self::getSandboxClient();
        $resp=$client->queryWithholdRefund($queryWithholdRefundRequest);
        var_dump(obToArray($resp));
    }

    /**
     * 关闭订单
     * 关闭订单的前提：
     * 1. 用户履约完成
     * 2. 取消代扣计划：租转售或者退租成功
     *
     * @param
     */
    public static function closeOrder($orderId)
    {
        $syncTradeRequest = new SyncTradeRequest([
            "bizContent" => json_encode(['orderId'=>$orderId]),
            "type" => "closeOrder"
        ]);

        $client = self::getSandboxClient();

        $resp =  $client->syncTrade($syncTradeRequest);
        return obToArray($resp);
    }

    /**
     * 清偿清欠
     * 取消某一期代扣
     * @param orderId
     * @param peroid
     * @param amount
     * @return
     * @
     */
    public static function repayWithholdPlan($orderId, $peroid, $amount)
    {
        $repayWithholdPlanRequest = new RepayWithholdPlanRequest([
            "gmtPay" => date('c',time()),
            "orderId" => $orderId,
            "payOffAmount" => $amount*100,
            "payOffNo" => time(),
            "payOffType" => "WECHAT",
            "periodNum" => $peroid
        ]);

        $client = self::getSandboxClient();

        $resp =  $client->repayWithholdPlan($repayWithholdPlanRequest);

        self::requestLog(' 取消某一期代扣', ['orderId'=>$orderId],obToArray($resp));

        return obToArray($resp);
    }

    /**
     * 接触代扣绑定
     *
     * @param orderId
     * @
     */
    public static function unbindWithholdSign($orderId)
    {
        $unbindWithholdSignRequest = new UnbindWithholdSignRequest([
            "orderId" => $orderId
        ]);

        $client = self::getSandboxClient();

        echo "unbindWithholdSign-req: <br/>";
        var_dump($unbindWithholdSignRequest);
        $resp = $client->unbindWithholdSign($unbindWithholdSignRequest);
        echo "<br/>";
        echo "unbindWithholdSign-resp: <br/>";
        var_dump($resp);
    }

    /**
     * 发起代扣签约请求
     *
     * @param orderId
     * @return
     * @
     */
    public static function createWithholdSign($orderId)
    {
        $createWithholdSignRequest = new CreateWithholdSignRequest([
//            "alipayMerchantId" => "2088********47",
//            "alipayMerchantName" => "商户名称",
//            "alipayMerchantServiceDescription" => "商户服务描述",
//            "alipayMerchantServiceName" => "商户服务名称",
            "orderId" => $orderId
        ]);

        $client = self::getSandboxClient();

        $resp = $client->createWithholdSign($createWithholdSignRequest);
        self::requestLog(' 发起代扣签约请求', ['orderId'=>$orderId],obToArray($resp));

        return obToArray($resp);
    }

    /**
     * 查询代扣签约结果
     *
     * @param orderId
     * @
     */
    public static function queryWithholdSign($orderId)
    {
        $queryWithholdSignRequest = new QueryWithholdSignRequest([
            "orderId" => $orderId
        ]);

        $client = self::getSandboxClient();


        $resp = $client->queryWithholdSign($queryWithholdSignRequest);
        return obToArray($resp);
    }

    /**
     * 取消代扣计划
     *
     * @param orderId
     * @
     */
    public static function cancelWithholdPlan($orderId)
    {
        $cancelWithholdPlanRequest = new CancelWithholdPlanRequest([
            "cancelReason" => "RENTING_AND_RESALE",
            "orderId" => $orderId
        ]);

        $client = self::getSandboxClient();


        $resp = $client->cancelWithholdPlan($cancelWithholdPlanRequest);

        return obToArray($resp);
    }

    /**
     * 异步解约确认
     *
     * @param orderId
     * @param operate
     * @param userInService
     * @param userOwnMoney
     * @param refuseReasonCode
     * @return
     * @
     */
    public static function asyncUnbindConfirm($orderId, $operate, $userInService, $userOwnMoney, $refuseReasonCode)
    {
        if($userOwnMoney){
            $confirmWithholdSignasyncunsignRequest = new ConfirmWithholdSignasyncunsignRequest([
                "operate" => $operate,
                "orderId" => $orderId,
                "refuseReasonCode" => $refuseReasonCode,
                "userInService" => $userInService,
                "userOweMoney" => $userOwnMoney
            ]);
        }else{
            $confirmWithholdSignasyncunsignRequest = new ConfirmWithholdSignasyncunsignRequest([
                "operate" => $operate,
                "orderId" => $orderId,
                "refuseReasonCode" => $refuseReasonCode,
                "userInService" => $userInService,
            ]);
        }


        $client = self::getSandboxClient();


        $resp = $client->confirmWithholdSignasyncunsign($confirmWithholdSignasyncunsignRequest);
        return obToArray($resp);

    }

    /**
     * 商户落章
     *
     * @param signNo
     * @param tag
     * @
     */
    public static function callAuthSignField($signNo, $tag)
    {
        $authSignFlowRequest = new AuthSignFlowRequest([
            "signNo" => "signNo", // 此处需要替换为签约号
            "tag" => $tag
        ]);
        $client = self::getSandboxClient();

        echo "callAuthSignField-req: <br/>";
        var_dump($authSignFlowRequest);
        $resp = $client->authSignFlow($authSignFlowRequest);
        echo "<br/>";
        echo "callAuthSignField-resp: <br/>";
        var_dump($resp);
    }

    /**
     * 同步分账信息(OK)
     *
     * @param orderId
     * @
     */
    public static function syncSplitting($orderId)
    {

        $syncFundSplittingRequest = new SyncFundSplittingRequest([
            "fundNo" => "78161205541791802849",
            "merchantTenantId" => "",
            "orderId" => "8573863c9aa2424e98cd80190a0f927e",
            "termNum" => 15
        ]);
        $client = self::getSandboxClient();

        echo "syncSplitting-req: <br/>";
        var_dump($syncFundSplittingRequest);
        $resp = $client->syncFundSplitting($syncFundSplittingRequest);
        echo "<br/>";
        echo "syncSplitting-resp: <br/>";
        var_dump($resp);
    }

    /**
     * 查询签署合同流程（OK）
     *
     * @param signNo
     * @return
     * @
     */
    public static function querySignFlow($signNo)
    {
        $getSignFlowRequest = new GetSignFlowRequest([
            "signNo" => $signNo
        ]);

        $client = self::getSandboxClient();


        $resp = $client->getSignFlow($getSignFlowRequest);

        self::requestLog(' 查询签署合同流程', ['orderId'=>$signNo],obToArray($resp));

        return obToArray($resp);
    }

    /**
     * 查询订单信息
     * @param orderId
     * @return
     * @
     */
    public static function queryOrder($orderId)
    {

        $getTradeRequest = new GetTradeRequest([
            "bizContent" => "{\"orderId\":\"{$orderId}\"}",
            "type" => "orderFullInfo"
        ]);

        $client = self::getSandboxClient();


        $resp = $client->getTrade($getTradeRequest);

        return obToArray($resp);
    }

    /**
     * 同步前置订单
     * 创建订单
     * @param orderId
     * @return
     * @
     */
    public static function syncFrontOrder($order)
    {
//        return $order;
        $productId = $order['order_goods_id'].rand(100,999);
        $merchantId = config('antchainjuzu.merchantId');
        $productVersion = "1";

        // 同步商品信息，如果不存在的话
        $product=self::syncProductIfNotExist($productId, $productVersion, $merchantId,$order);
        $product=json_decode($product['responseData'],true);
        $orderLease = OrderLease::where('order_id',$order['id'])->select('id','begin_time','rent','which_period')->orderBy('id','asc')->get();
        $repayStrategyList=[];
        foreach ($orderLease as $k=>$v){
            $repayStrategyList[]=[
                "termIndex" => $v['which_period'],
                "rentalMoney" => $v['rent']*100,
                "payDay" => date('Y-m-d',$v['begin_time']),
            ];
        }
        if(!strstr($order['address'],'省')&&!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }

        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        $bizInfo= [
            "userInfo" => [
                "loginId" => $order['uid'],
                "loginTime" => date('Y-m-d H:i:s'),
                "leaseCorpName" => str_replace('-','',$order['company_area']).$order['company'],
                "lesseeType" => 2,
                "loginType" => 2,
                "leaseCorpOwnerName" => $order['faname'],
                "leaseCorpId" => $order['companyid'],
                "userPhoneNumber" => self::encryptInDev($order['user_mobile']),
                "userName" =>self::encryptInDev($order['cert_name']),
                "userId" => self::encryptInDev($order['cert_no']),
                "alipayUID" => $order['user_id']
            ],
            "orderId" => $order['trade_no'],
            "merchantId" =>  config('antchainjuzu.merchantId'),
            "merchantName"=> config('antchainjuzu.merchantName'),
            "promiseInfo" => [
                "gracePeriodDays" => 3,
                "punishmentType" => "NONE",
                "payPeriod" => $order['month_total'],
                "repayStrategyList" => $repayStrategyList,
                "leaseAlipayUid" =>config('alipay.alipayUID')
            ],
            "orderInfo" => [
                "logisticType" => "POST",
                "orderCreateTime" =>date('Y-m-d H:i:s',$order['create_time']),
                "rentUnit" => "MONTH",
                "orderPaySubject" => $order['goods_title'].$order['setmeal_title'],
                "totalRentMoney" => bcmul($order['rent_total'],100),
                "orderPayBody" =>$order['goods_title'].$order['setmeal_title'],
                "userAutoSign" => false,
                "userAddress" =>  $order['address'],
                "rentPricePerMonth" => bcmul($month_rent,100),
                "buyOutPrice" => $order['pact_type']==1?bcmul($order['setmeal_foregift'],100):'',
                "dueMode" => $order['pact_type'],
                "rentTerm" => $order['month_total']
            ],
            "bizScene" => "CHARGING_BY_TERM",
            "productInfo" => [
                "productInfo" => [
                    "0" => [
                        "productVersion" => $product['productVersion'],
                        "productId" => $product['productId'],
                        "productNumber" => 1,
                        "productItemList" => [
                            "0" => [
                                "productImeiId" => "c4db7bd1-c739-4227-8244-40785ed6cbd0",
                                "purchaseAmt" =>bcmul($order['setmeal_foregift'],100)
                            ]
                        ]
                    ]
                ]
            ]
        ];

        // bizcontent参考官网文档说明
        $syncFrontTradeRequest = new SyncFrontTradeRequest([
            "bizContent" => json_encode($bizInfo),
            "type" => "orderFullInfo"
        ]);

        $client = self::getSandboxClient();

        $resp = $client->syncFrontTrade($syncFrontTradeRequest);

        dd(obToArray($resp));

    }

    /**
     * 同步后置订单
     * @param orderId
     * @return
     * @
     */
    public static function syncBehindOrder($order)
    {

        $productId = $order['order_goods_id'].rand(100,999);
        $merchantId = config('antchainjuzu.merchantId');
        $productVersion = "1";

        // 同步商品信息，如果不存在的话
        $product=self::syncProductIfNotExist($productId, $productVersion,$merchantId,$order);
        $product=json_decode($product['responseData'],true);
        $orderLease = OrderLease::where('order_id',$order['id'])->select('id','begin_time','end_time','rent','which_period')->orderBy('id','asc')->get();
        $repayStrategyList=[];
        $begin_time=0;
        foreach ($orderLease as $i=>$ra){
//            $amount_rent+=bcmul($ra['rent'],100);
            if($ra['which_period']==1){
                if($ra['begin_time']>time()+3600){
                    $begin_time=$ra['begin_time'];
                }else{
                    $ra['begin_time']=time()+3600;
                    $begin_time=time()+7200;
                }
            }else{
                if(date("d",$begin_time)>=28){
                    $ra['begin_time']=strtotime('last day of + 1 month',$begin_time);
                    $begin_time=strtotime('last day of + 1 month',$begin_time);
                }else{
                    $ra['begin_time']=strtotime('+ 1 month',$begin_time);
                    $begin_time=strtotime('+ 1 month',$begin_time);
                }

            }
            $repayStrategyList[]=[
                "termIndex" => $ra['which_period'],
                "rentalMoney" => bcmul($ra['rent'],100),
                //"rentalMoney" => $ra['rent']*100,
                "payDay" => date('Y-m-d',$begin_time),// date('Y-m-d',$begin_time])
            ];
        }

        if(!strstr($order['address'],'省')&&!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }

        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        $bizInfo= [
            "userInfo" => [
                "loginId" => $order['uid'],
                "loginTime" => date('Y-m-d H:i:s'),
                "leaseCorpName" =>$order['company'],
                "lesseeType" => 2,
                "loginType" => 2,
                "leaseCorpOwnerName" => $order['faname'],
                "leaseCorpId" => $order['companyid'],
                "userPhoneNumber" => self::encryptInDev($order['user_mobile']),
                "userName" =>self::encryptInDev($order['cert_name']),
                "userId" => self::encryptInDev($order['cert_no']),
                "alipayUID" => $order['user_id']
            ],
            "orderId" => $order['trade_no'],
//            "merchantId" => $order['companyid'],
//            "merchantName"=> $order['mechanism'],
            "merchantId" => config('antchainjuzu.merchantId'),
            "merchantName"=> config('antchainjuzu.merchantName'),
            "promiseInfo" => [
                "gracePeriodDays" => 0,
                "punishmentType" => "NONE",
                "payPeriod" => $order['month_total'],
                "repayStrategyList" => $repayStrategyList,
                "leaseAlipayUid" =>config('alipay.alipayUID')
            ],
            "orderInfo" => [
                "logisticType" => "POST",
                "orderCreateTime" =>date('Y-m-d H:i:s',$order['create_time']),
                "rentUnit" => "MONTH",
                "orderPaySubject" => $order['goods_title'].$order['setmeal_title'],
                "totalRentMoney" => bcmul($order['rent_total'],100),
                "orderPayBody" =>$order['goods_title'].$order['setmeal_title'],
                "userAutoSign" => false,
                "userAddress" =>  $order['address'],
                "rentPricePerMonth" =>  bcmul($month_rent,100),
                "buyOutPrice" => $order['pact_type']==1? bcmul($order['setmeal_foregift'],100):'',
                "dueMode" => $order['pact_type'],
                "rentTerm" => $order['month_total']
            ],
            "bizScene" => "CHARGING_BY_TERM",
            "productInfo" => [
                "productInfo" => [
                    "0" => [
                        "productVersion" => $product['productVersion'],
                        "productId" => $product['productId'],
                        "productNumber" => 1,
                        "productItemList" => [
                            "0" => [
                                'productImeiId'=> $product['productId'],
                                "purchaseAmt" =>bcmul($order['setmeal_foregift'],100)
                            ]
                        ]
                    ]
                ]
            ]
        ];

        $syncTradeRequest = new SyncTradeRequest([
            "bizContent" =>  json_encode($bizInfo),
            "type" => "orderFullInfo"
        ]);

        $client = self::getSandboxClient();

        $resp = $client->syncTrade($syncTradeRequest);
//        var_dump($resp);
        return obToArray($resp);
    }

    /**
     * 同步商品信息
     *
     * @param productId
     * @param productVersion
     * @param merchantId
     * @
     */
    public static function syncProductIfNotExist($productId, $productVersion,$merchantId, $order)
    {
        $product=['productId'=>$productId,'productVersion'=>$productVersion,'merchantId'=>$merchantId];

        $getTradeRequest = new GetTradeRequest([
            "bizContent" => json_encode($product),
            "type" => "product"
        ]);

        $client = self::getSandboxClient();

        $resp = $client->getTrade($getTradeRequest);

        // 如果获取不到商品, 则新建商品
        if ($resp->responseData  == "") {
            $product=[
                "productId" => $productId,
                "productVersion" => $productVersion,
                "merchantId" => $merchantId,
                "productDetailInfo" => "商品详情",
                "productName" =>$order['goods_title'],
                "productPrice" => bcmul($order['setmeal_foregift'],100),
                "productUrl" => "alipays://platformapi/startapp?appId=2021004114640041&page=pagesA%2Fpages%2FproductDetails%2FproductDetails%3F__appxPageId%3D1%26goodsId%3D".$order['goods_id'],
                "productBrand" => "iphone",
                "productModel" =>$order['setmeal_title'],
                "mainClass" => "3C",
                "subClass" => "3c_mobile",
            ];

            $syncTradeRequest = new SyncTradeRequest([
                "bizContent" => json_encode($product),
                "type" => "product"
            ]);
            $client = self::getSandboxClient();

            $resp=$client->syncTrade($syncTradeRequest);
        }
        return obToArray($resp);
    }

    /**
     * 提交前置合同
     * @param orderId
     * @
     */
    public static function submitFrontSignFlow($orderId)
    {

        $thirdSigner[] = [
            "orgIdNumber" => self::encryptInDev("丙方证件号"),
            "orgLegalName" => self::encryptInDev("丙方法人姓名"),
            "orgName" => "xxxxxx",
            "orgIdType" => "CRED_ORG_USCC",
            "tag" => "bingfang",
            "orgLegalIdNumber" => self::encryptInDev("丙方证件号"),
        ];

        $submitFrontSignRequest = new SubmitFrontSignRequest([
            "alipayUserId" => "2088xx1312312323",
            "businessScene" => "租赁协议",
            "flowNotifyType" => "1",
            "merchantIdNumber" => self::encryptInDev("商户证件号，需要和订单进件的merchantId保持一致"),
            "merchantIdType" => "CRED_ORG_USCC",
            "merchantLegalIdNumber" => self::encryptInDev("法人证件号"),
            "merchantLegalName" => self::encryptInDev("法人姓名"),
            "merchantName" => "商户名称，需要保证传递政策",
            "merchantTag" => "甲方",
            "orderId" => $orderId,
            "signedRedirectUrl" => "https://www.alipay.com",
            "templateList" => "[{\"templateId\":\"合同模板ID\",\"templateArgs\":{\"companytel\":\"公司联系电话\",\"companyadd\":\"公司联系地址\"}}]",
            "thirdSigner" => json_encode($thirdSigner),
            "userEmail" => self::encryptInDev("用户email"),
            "userIdNumber" => self::encryptInDev("身份证号"),
            "userIdType" => "CRED_PSN_CH_IDCARD",
            "userMobile" => self::encryptInDev("180xxxx"),
            "userName" => self::encryptInDev("用户姓名"),
        ]);

        $client = self::getSandboxClient();

        echo "submitFrontSignFlow-req: <br/>";
        var_dump($submitFrontSignRequest);
        $resp = $client->submitFrontSign($submitFrontSignRequest);
        echo "<br/>";
        echo "submitFrontSignFlow-resp: <br/>";
        var_dump($resp);

        echo "<br/>";
        echo "submitBehindSignFlow-resp-signNo: <br/>";
        var_dump($resp->signNo);

        return $resp->signNo;
    }

    /**
     * 提交后置合同
     *
     * @param orderId
     * @
     */
    public static function submitBehindSignFlow($order)
    {
        $first_month_rent = OrderLease::where('order_id',$order['id'])->where("which_period",1)->value("rent");
        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        if(!strstr($order['address'],'省')||!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }

        $order_data = [
            'trade_no' => $order['trade_no'],
            'order_sn' => $order['trade_no'],
            'first_name' => $order['mechanism'],
            'first_rent' => '0',
            'first_address' => str_replace('-','',$order['company']),
            'first_code' => $order['companyid'],
            'first_mobile' => $order['contact_tel'],
            'companyname'=> config('antchainjuzu.merchantName'),
            'companyid' => config('antchainjuzu.merchantId'),
            'serial_number' => '',
            'user_name' => $order['cert_name'],
            'user_address' => $order['address'],
            'user_idcard' => $order['cert_no'],
            'user_mobile' => $order['user_mobile'],
            'mobile' => $order['user_mobile'],
            'third_name' => '杭州哆莱智能科技有限公司',
            'third_address' => '浙江省杭州市西湖区翠苑街道文三路477号华星科技大厦212室',
            'third_code' => '91330114MA8GEH9L88',
            'third_mobile' => '19357312131',
            'order_no' => $order['trade_no'],
            'user_data' => $order['cert_name'].'('.$order['cert_no'].')',
            'productname' => $order['goods_title'],
            'setmeal_name' => $order['setmeal_title'],
            'set_meal' => $order['setmeal_title'],
            'goods_title' => $order['goods_title'],
            'delivery_method' => '快递物流',
            'deposit_price'=> $order['cash_pledge']??'0',
            'amount' => $order['amount'],
            'explain'=>'',
            'is_new' => GoodsService::getGoodsNewGrade($order['new_grade']),
            'meal' => $order['pact_type'],
            'first_month_rent'=>$first_month_rent.'元',
            'total_rent1' => $order['rent_total'].'元',
            'month_rent' => $month_rent,
            'lease_term' =>  date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time'])),
            'pay_type' => '分期付租',
            'orderbuamta' => $order['pact_type']==1?$order['setmeal_price']:'0',
            'buy_out_price' => $order['cash_pledge']?$order['cash_pledge'].'元':'0元',
            'receiving_address' => $order['address'],
            'user_name1' => $order['cert_name'],
            'user_mobile1' => $order['user_mobile'],
            'user_address1' => $order['address'],
            'useraddr' => $order['address'],
            'email'=>$order['user_email'],
            'first_name1' => $order['mechanism'],
            'first_mobile1' => $order['contact_tel'],
            'first_address1' =>$order['company'],
            'first_name2' => $order['mechanism'],
            'jiafang_name' => $order['mechanism'],
            'jiafang_id' => $order['companyid'],
            'user_name2' => $order['cert_name'],
            'third_name2' => '杭州哆莱智能科技有限公司',
            'sign_year' => date("Y"),
            'sign_month' => date("m"),
            'sign_day' => date("d"),
            'date' => date("Y年m月d日"),
            'insurance_price' => GoodsService::getGoodsInsurance($order['is_insurance_choose']).'元（与第一期租金一并支付）',
        ];
        $templateList=['templateId'=>config('antchainjuzu.templateId'),'contractType'=>'LEASE','agreementType'=>'LEASE'];
        $templateList['templateArgs']=$order_data;
        $templateListArr[]=$templateList;


        $submitSignFlowRequest = new SubmitSignFlowRequest([
            "alipayUserId" => $order['user_id'],
            "businessScene" => "商品销售服务协议",
            "flowNotifyType" => "1",
            "merchantIdNumber" =>  self::encryptInDev(config('antchainjuzu.merchantId')),
            "merchantIdType" => "CRED_ORG_USCC",
            "merchantLegalIdNumber" => self::encryptInDev(config('antchainjuzu.orgLegalIdNumber')),
            "merchantLegalName" => self::encryptInDev(config('antchainjuzu.orgLegalName')),
            "merchantName" => config('antchainjuzu.merchantName'),
            "merchantTag" => "yifang",
            "orderId" => $order['trade_no'],
            "signedRedirectUrl" => "https://h5shop.doulaizuji.com/order.html?order_id=".$order['id'],
            "templateList" => json_encode($templateListArr),
            "userEmail" => self::encryptInDev($order['email']),
            "userIdNumber" => self::encryptInDev($order['cert_no']),
            "useridnum" => $order['cert_no'],
            "userIdType" => "CRED_PSN_CH_IDCARD",
            "userMobile" => self::encryptInDev($order['user_mobile']),
            "userName" => self::encryptInDev($order['cert_name']),
        ]);

        $client = self::getSandboxClient();

//        dd(obToArray($submitSignFlowRequest));

        $resp = $client->submitSignFlow($submitSignFlowRequest);


        self::requestLog('租赁平台提交合同', $order,obToArray($resp));
        return obToArray($resp);
    }

    /**
     * 智能合同日志记录
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function requestLog($message,$request=[],$response=[])
    {
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::channel("antchain")->debug($message,$content);
    }



    /**
     * 用户履约信息查询（履约承诺+记录）
     * @param $orderId
     * @return array
     */

    public static function getTradeUserperformance($orderId){
        $getTradeUserperformanceRequest = new GetTradeUserperformanceRequest([
            "merchantId" => config('antchainjuzu.merchantId'),
            "orderId" => $orderId
        ]);
        $client = self::getSandboxClient();
        $resp = $client->getTradeUserperformance($getTradeUserperformanceRequest);
        $res=obToArray($resp);
        $res['responseData']=json_decode($res['responseData'],true);
        return $res;
    }



    /**
     * 使用RSA进行加密
     *
     * @param content
     * @return
     * @
     */
    private static function encryptInDev($content)
    {
        $public_key = "-----BEGIN PUBLIC KEY-----\n" . self::$PROD_PUK . "\n-----END PUBLIC KEY-----";
        return self::encryptByPublicKey($content, openssl_pkey_get_public($public_key));
    }

    /**
     * 使用公钥进行RSA非对称加密
     *
     * @param data
     * @param key
     * @return
     * @
     */
    public static function encryptByPublicKey($data, $key)
    {
        if (!is_string($data)) {
            return null;
        }
        $r = openssl_public_encrypt($data, $encrypted,  $key);
        return base64_encode($encrypted);
    }

    /**
     * 创建生产环境的Client，使用生产环境的ak和sk
     * @param ak
     * @param sk
     * @return
     * @
     */
    private static function getProdClient()
    {
        if (self::$client == null) {
            $config = new Config([]);
            // 您的AccessKey ID
            $config->accessKeyId = config('antchainjuzu.accessKeyId');
            // 您的AccessKey Secret
            $config->accessKeySecret = config('antchainjuzu.accessKeySecret');
            // endpoint
            $config->endpoint = "openapi.antchain.antgroup.com";
            // 协议类型
            $config->protocol = "https";
            // echo json_encode($config);
            self::$client = new AntChainATOClient($config);
        } else {

        }
        return self::$client;
    }


    /**
     * 创建开发环境的Client,使用生产环境的ak和sk
     * @param ak
     * @param sk
     * @return
     * @
     */
    private static function getSandboxClient()
    {
        if (self::$client == null) {
            $config = new Config([]);
            //    'accessKeyId'=>'ACz3EK4m8sEW6VuC',
            //    'accessKeySecret'=>'SNVoK4ZQNT85kMYkejvx9TdeVaEjmj41',
            // 您的AccessKey ID
            $config->accessKeyId = config('antchainjuzu.accessKeyId');
            // 您的AccessKey Secret
            $config->accessKeySecret = config('antchainjuzu.accessKeySecret');
            // endpoint
            $config->endpoint = "openapi.antchain.antgroup.com";
            // 协议类型
            $config->protocol = "https";
//            $config->endpoint = "openapi-sit.antchain.dl.alipaydev.com";
//            // 协议类型
//            $config->protocol = "http";
            // echo json_encode($config);
            self::$client = new AntChainATOClient($config);
        }
        return self::$client;
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function uploadSignTemplate(){
        $posConf=[
            ['tag'=>'jiafang','signerType'=>'ORGANIZATION','posPage'=>'17','posX'=>'190','posY'=>'705'],
            ['tag'=>'yifang','signerType'=>'PERSON','posPage'=>'17','posX'=>'190','posY'=>'573'],
            ['tag'=>'bingfang','signerType'=>'ORGANIZATION','posPage'=>'17','posX'=>'190','posY'=>'434','sealId'=>'a69698d2-416b-4938-a5e7-9f3eb4c7ba00']
        ];
        $content = file_get_contents('D:\phpstudy_pro\WWW\zdoulaizuji\都来租赁赁合同支付宝端202412016.pdf');
        $uploadSignTemplateRequest = new UploadSignTemplateRequest([
            "contractType" => "LEASE",
            "posConf" => json_encode($posConf),
            "agreementType" => "LEASE",
            "fileObjectName" => "聚租商城.pdf",
            "merchantId" =>  config('antchainjuzu.merchantId'),
            "fileObject" => $content
        ]);
        $client = self::getSandboxClient();
        $res= $client->uploadSignTemplate($uploadSignTemplateRequest);
        return obToArray($res);
    }

}

